<template>
	<div style="padding-left: 20px; height: 100%; overflow: auto">
		<el-tabs v-model="activeName">
			<el-tab-pane name="basicInfo">
				<template #label>
					<span>
						<el-icon><Postcard /></el-icon>&nbsp;
						<span>基本信息</span>
					</span>
				</template>
				<div>
					<el-descriptions title="概述" :column="1" border size="large" direction="horizontal">
						<el-descriptions-item label="名称">{{ bisData.name }}</el-descriptions-item>
						<el-descriptions-item label="编码">{{ bisData.code }}</el-descriptions-item>
						<el-descriptions-item label="元数据类型">{{ bisData.metamodel }}</el-descriptions-item>
						<el-descriptions-item label="路径">{{ bisData.path }}</el-descriptions-item>
						<el-descriptions-item label="创建时间">{{ bisData.createTime }}</el-descriptions-item>
						<el-descriptions-item label="描述">{{ bisData.description }}</el-descriptions-item>
					</el-descriptions>
				</div>
				<br />
				<div v-show="hasProperty">
					<el-descriptions title="属性信息" :column="2" border size="large" direction="horizontal">
						<el-descriptions-item v-for="(item, index) in metaProperties" :label="item.name">{{ item.value }}</el-descriptions-item>
					</el-descriptions>
				</div>
			</el-tab-pane>
			<el-tab-pane v-if="canStandard" name="dataStandard" style="height: 580px; overflow: auto; padding-top: 80px">
				<template #label>
					<span>
						<el-icon><Menu /></el-icon>&nbsp;
						<span>数据标准</span>
					</span>
				</template>
				<div
					style="
						position: absolute;
						top: 0;
						left: 0;
						padding: 8px 24px 24px 8px;
						box-sizing: border-box;
						width: 100%;
						background: #fff;
						z-index: 10;
						border-bottom: 1px solid #e5e6eb;
					"
				>
					<el-button type="primary" style="float: right" @click="addStandard">新增关联标准</el-button>
				</div>
				<div v-for="(item, index) of metaDataList" :key="index">
					<el-form>
						<el-form-item label="关联标准" prop="standardCategoryId">
							<el-tree-select v-model="item.standardCategoryId" :data="standardCategoryList" clearable @change="standardCategoryChange(item)">
								<template #default="{ node, data }">
									<div>
										<span>
											<img v-if="data.type == 0" src="/src/assets/folder.png" />
											<img v-if="data.type == 1" src="/src/assets/column.png" />
											<img v-if="data.type == 2" src="/src/assets/table.png" />
											<span style="margin-left: 8px">{{ data.name }}</span>
										</span>
									</div>
								</template>
							</el-tree-select>
							<el-radio
								v-show="item.standardCategoryId && item.id"
								v-model="theDefault"
								:label="item.id"
								style="margin-left: 20px"
								@click="setDefault(item)"
								>默认</el-radio
							>
						</el-form-item>
					</el-form>
					<div v-show="!!item.standardCategoryId">
						<el-form :inline="true" :model="item.state.queryForm" @keyup.enter="item.copyGetDataList(item.state)">
							<el-form-item>
								<el-input v-model="item.state.queryForm.engName" placeholder="英文名称"></el-input>
							</el-form-item>
							<el-form-item>
								<el-input v-model="item.state.queryForm.cnName" placeholder="中文名称"></el-input>
							</el-form-item>
							<el-form-item>
								<el-button type="primary" @click="item.copyGetDataList(item.state)">查询</el-button>
							</el-form-item>
						</el-form>
						<el-table v-loading="item.state.dataListLoading" :data="item.state.dataList" border style="width: 100%">
							<el-table-column prop="engName" label="英文名称" header-align="center" align="center"></el-table-column>
							<el-table-column prop="cnName" label="中文名称" header-align="center" align="center"></el-table-column>
							<fast-table-column
								prop="dataType"
								dict-type="standard_data_type"
								label="数据类型"
								header-align="center"
								align="center"
							></fast-table-column>
							<el-table-column prop="dataLength" label="长度" header-align="center" align="center"></el-table-column>
							<el-table-column prop="dataPrecision" label="精度" header-align="center" align="center"></el-table-column>
							<fast-table-column prop="nullable" dict-type="yes_or_no" label="可为空" header-align="center" align="center"></fast-table-column>
							<fast-table-column prop="type" dict-type="standard_type" label="类型" header-align="center" align="center"></fast-table-column>
							<fast-creator-column prop="creator" label="创建者" header-align="center" align="center"></fast-creator-column>
							<el-table-column prop="createTime" show-overflow-tooltip label="创建时间" header-align="center" align="center"></el-table-column>
							<el-table-column label="操作" fixed="right" header-align="center" align="center" width="230">
								<template #default="scope">
									<el-button type="primary" link @click="getInfo(scope.row.id)">查看</el-button>
									<el-button v-show="scope.row.ifStandardRel" type="primary" link @click="standardCheck(scope.row.id)">标准检测</el-button>
									<el-button v-show="!scope.row.ifStandardRel" type="primary" link @click="rel(item, scope.row.id)">关联</el-button>
									<el-button v-show="scope.row.ifStandardRel" type="primary" link @click="delRel(item, scope.row.id)">取消关联</el-button>
								</template>
							</el-table-column>
						</el-table>
						<el-pagination
							:current-page="item.state.page"
							:page-size="item.state.limit"
							:page-sizes="item.state.pageSizes"
							:total="item.state.total"
							layout="total, sizes, prev, pager, next, jumper"
							@size-change="val => item.copySizeChangeHandle(val, item)"
							@current-change="val => item.copyCurrentChangeHandle(val, item)"
						>
						</el-pagination>
					</div>
					<el-divider />
				</div>
			</el-tab-pane>
			<el-tab-pane v-if="bisData.metamodelId == 2" name="dataSynchronous">
				<template #label>
					<span>
						<el-icon><Share /></el-icon>&nbsp;
						<span>表信息</span>
					</span>
				</template>
				<div>
					<div style="display: flex; justify-content: space-between; margin-bottom: 10px">
						<div>
							<el-select v-model="tableState" @change="stateChange">
								<el-option label="全部" value="" />
								<el-option label="未建表" value="undo" />
								<el-option label="建表成功" value="success" />
								<el-option label="建表失败" value="failed" />
							</el-select>

							<!-- <el-button type="primary" style="margin-left: 10px;" @click="modelCloseCall">刷新</el-button> -->
						</div>
						<div>
							<el-button type="primary" @click="addTable">批量建表</el-button>
							<el-button type="primary" @click="addTask">批量创建同步任务</el-button>
						</div>
					</div>
					<div>
						<el-table :data="tableInfoData" border style="width: 100%">
							<el-table-column label="编号" type="index" width="80"></el-table-column>
							<el-table-column prop="code" label="表名" header-align="center" align="center"></el-table-column>
							<el-table-column prop="label" label="表注释" header-align="center" align="center"></el-table-column>
							<el-table-column prop="targetDatabase" label="目标模式" header-align="center" align="center"></el-table-column>
							<el-table-column prop="targetTableCode" label="目标表名" header-align="center" align="center"></el-table-column>
							<el-table-column prop="tableCreateStatus" label="建表状态" header-align="center" align="center">
								<template #default="scope">
									<span v-if="scope.row.tableCreateStatus == 'undo' || !scope.row.tableCreateStatus"> 未建表 </span>
									<span v-if="scope.row.tableCreateStatus == 'success'"> 建表成功 </span>
									<span v-if="scope.row.tableCreateStatus == 'failed'">
										<el-popover placement="top-start" title="失败原因" :width="200" trigger="hover" :content="scope.row.tableCreateFailReason">
											<template #reference>
												<el-button type="primary" link>建表失败</el-button>
											</template>
										</el-popover>
									</span>
								</template>
							</el-table-column>
							<el-table-column prop="syncStatus" label="创建任务状态" header-align="center" align="center">
								<template #default="scope">
									<div v-if="scope.row.syncStatus" style="display: flex; align-items: center; justify-content: center">
										已创建 &nbsp;<el-icon color="#4a7904"><CircleCheck /></el-icon>
									</div>
									<div v-else style="display: flex; align-items: center; justify-content: center">
										未创建 &nbsp;<el-icon color="#bd3124"><CircleClose /></el-icon>
									</div>
								</template>
							</el-table-column>
						</el-table>
						<el-pagination
							:current-page="pagination.page"
							:page-sizes="pagination.pageSizes"
							:page-size="pagination.limit"
							:total="pagination.total"
							layout="total, sizes, prev, pager, next, jumper"
							@size-change="sizeChange"
							@current-change="currentChange"
						>
						</el-pagination>
					</div>
				</div>
			</el-tab-pane>
		</el-tabs>
		<StandardInfo ref="standardInfoRef"></StandardInfo>
		<StandardCheck ref="standardCheckRef"></StandardCheck>

		<AddTables ref="addTablesRef" @close="modelCloseCall"></AddTables>
		<AddTasks ref="addTasksRef" @close="modelCloseCall"></AddTasks>
	</div>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted, nextTick } from 'vue'
import store from '@/store'
import { useMetamodelApi } from '@/api/data-governance/metamodel'
import { useMetadataApi, getMetadataSyncPage, getMetadataSyncTask } from '@/api/data-governance/metadata'
import { listTreeApi, dataStandardCheckApi } from '@/api/data-governance/dataStandard'
import { getByMetadataApi, useStandardRelSubmitApi, delMetadataRelApi, setDefaultApi, cancelDefaultApi } from '@/api/data-governance/standardRel'
import service from '@/utils/request'
import StandardInfo from '../data-standard/standard-info.vue'
import StandardCheck from '../data-standard/standard-check.vue'
import { ElMessage, ElMessageBox, ElNotification } from 'element-plus/es'

import AddTables from './addTables.vue'
import AddTasks from './addTasks.vue'

onMounted(() => {
	//加载数据标准树
	listTreeApi().then(res => {
		standardCategoryList.value = res.data
	})
})

/**
 * 基本信息
 */
const bisData = reactive({
	name: '',
	code: '',
	path: '',
	metamodel: '',
	builtin: '',
	description: ''
})

const activeName = ref('basicInfo')
const theDefault = ref()
const metaProperties = ref([])
const metaDataList = ref([])
const hasProperty = ref(false)
const canStandard = ref(false)
const standardCategoryList = ref([])
const metadataId = ref()
const tableInfoData = ref([])
const tableState = ref('success')

const init = (data: any) => {
	tableState.value = 'success'
	//赋值给基本信息
	Object.assign(bisData, data)
	canStandard.value = data.metamodelId == 4
	if (data.metamodelId != 4) {
		activeName.value = 'basicInfo'
	}
	metadataId.value = data.id
	//根据元模型id获取元模型
	useMetamodelApi(data.metamodelId).then(res => {
		bisData.metamodel = res.data.path
	})
	//获取属性列表
	useMetadataApi(data.id).then(res => {
		metaProperties.value = res.data.properties
		if (metaProperties.value.length > 0) {
			hasProperty.value = true
		} else {
			hasProperty.value = false
		}
	})
	//获取关联的数据标准
	getByMetadataApi(data.id).then(res => {
		metaDataList.value = []
		if (res.data.length > 0) {
			metaDataList.value = res.data
			if (res.data[0].auto == 0) {
				theDefault.value = res.data[0].id
			}
			metaDataList.value.forEach(item => {
				item.state = {
					createdIsNeed: false,
					dataListUrl: '/data-governance/data-standard/page',
					deleteUrl: '/data-governance/data-standard',
					isPage: true,
					dataList: [],
					page: 1,
					limit: 3,
					total: 0,
					pageSizes: [3, 5, 10, 20, 50],
					dataListLoading: false,
					queryForm: {
						ifMeta: true,
						categoryId: item.standardCategoryId,
						metadataId: item.metadataId,
						engName: '',
						cnName: ''
					}
				}
				item.copyGetDataList = getDataList
				item.copySizeChangeHandle = sizeChangeHandle
				item.copyCurrentChangeHandle = currentChangeHandle
				item.copyGetDataList(item.state)
			})
		}
	})

	// 点击数据库
	if (data.metamodelId == 2) {
		tableInfoData.value = []

		getMetaSyncData()
	}
}

const pagination = ref({
	page: 1,
	limit: 10,
	total: 0,
	pageSizes: [10, 20, 50, 100, 200]
})

const sizeChange = val => {
	pagination.value = {
		...pagination.value,
		page: 1,
		limit: val
	}
	getMetaSyncData()
}
const currentChange = val => {
	pagination.value = {
		...pagination.value,
		page: val
	}
	getMetaSyncData()
}

const stateChange = value => {
	tableState.value = value
	pagination.value.page = 1
	getMetaSyncData()
}

const modelCloseCall = () => {
	pagination.value.page = 1
	setTimeout(() => {
		getMetaSyncData()
	}, 1000)
}

// 获取表同步数据
const getMetaSyncData = () => [
	getMetadataSyncPage({
		parentId: bisData.id,
		page: pagination.value.page,
		limit: pagination.value.limit,
		tableCreateStatus: tableState.value
	}).then(res => {
		tableInfoData.value = res.data.list
		pagination.value.total = res.data.total
	})
]

// 获取表格数据
const getDataList = state => {
	state.dataListLoading = true
	service
		.get(state.dataListUrl, {
			params: {
				page: state.isPage ? state.page : null,
				limit: state.isPage ? state.limit : null,
				...state.queryForm
			}
		})
		.then((res: any) => {
			//console.log(preFun)
			// zrx 前置执行
			state.dataList = state.isPage ? res.data.list : res.data
			state.total = state.isPage ? parseInt(res.data.total) : 0
		})
		.finally(() => {
			state.dataListLoading = false
		})
}
// 修改最大展示条数
const sizeChangeHandle = (val: number, item) => {
	item.state.page = 1
	item.state.limit = val
	item.copyGetDataList(item.state)
}
// 修改当前页
const currentChangeHandle = (val: number, item) => {
	item.state.page = val
	item.copyGetDataList(item.state)
}

// 添加标准
const addStandard = () => {
	metaDataList.value.push({
		id: null,
		standardCategoryId: null,
		metadataId: metadataId.value,
		auto: 1,
		copyGetDataList: getDataList,
		copySizeChangeHandle: sizeChangeHandle,
		copyCurrentChangeHandle: currentChangeHandle,
		state: {
			createdIsNeed: false,
			dataListUrl: '/data-governance/data-standard/page',
			deleteUrl: '/data-governance/data-standard',
			isPage: true,
			dataList: [],
			page: 1,
			limit: 3,
			total: 0,
			pageSizes: [3, 5, 10, 20, 50],
			dataListLoading: false,
			queryForm: {
				ifMeta: true,
				metadataId: metadataId.value,
				engName: '',
				cnName: ''
			}
		}
	})
	console.log('新增', metaDataList.value)
}

// 设置默认关联标准
const setDefault = item => {
	if (theDefault.value == item.id) {
		cancelDefaultApi(item.id).then(res => {
			ElMessage.success('取消默认成功')
			theDefault.value = ''
		})
	} else {
		setDefaultApi(item.id, item.metadataId).then(res => {
			ElMessage.success('设置默认成功')
		})
	}
}

const standardCategoryChange = item => {
	if (item.standardCategoryId) {
		//获取数据标准列表
		item.state.queryForm.categoryId = item.standardCategoryId
		item.state.queryForm.metadataId = item.metadataId
		item.copyGetDataList(item.state)
	}
}

const standardInfoRef = ref()
const getInfo = id => {
	standardInfoRef.value.init(id)
}

const rel = (item, id) => {
	ElMessageBox.confirm('一个字段只能关联数据标准中的一个字段，若该字段已关联了当前标准中其他字段，将自动解除关联，确认关联吗？', {
		confirmButtonText: '是',
		cancelButtonText: '否',
		type: 'warning'
	})
		.then(() => {
			useStandardRelSubmitApi({
				metadataId: metadataId.value,
				standardId: id
			}).then(res => {
				ElMessage.success('关联成功')
				item.copyGetDataList(item.state)
				init(bisData)
			})
		})
		.catch(() => {})
}
const delRel = (item, id) => {
	ElMessageBox.confirm('确认取消关联吗？', {
		confirmButtonText: '是',
		cancelButtonText: '否',
		type: 'warning'
	})
		.then(() => {
			delMetadataRelApi(metadataId.value, id).then(res => {
				ElMessage.success('取消关联成功')
				item.copyGetDataList(item.state)
				init(bisData)
			})
		})
		.catch(() => {})
}

const standardCheckRef = ref()
const standardCheck = id => {
	dataStandardCheckApi(metadataId.value, id).then(res => {
		standardCheckRef.value.init(res.data)
	})
}

const addTablesRef = ref()
const addTasksRef = ref()
const addTable = () => {
	modelCloseCall()
	getAddTableIsTask()
}
const addTask = () => {
	addTasksRef.value.init(bisData, metaProperties.value)
}

// 获取是否有库表的建表任务
const getAddTableIsTask = () => {
	getMetadataSyncTask({ dataSourceName: bisData.code }).then(res => {
		if (res.data) {
			ElNotification({
				title: '提示',
				message: '批量建表任务正在执行中，不可批量建表',
				type: 'warning',
				duration: 2000
			})
		} else {
			addTablesRef.value.init(bisData, metaProperties.value)
		}
	})
}

defineExpose({
	init
})
</script>

<style></style>
